<template>
  <div>
    <div class="fix operate-top">
      <div class="flex center  ">
        <van-button class="btn" type="primary" @click="addAccount">新增</van-button>
        <van-button class="btn" type="primary" v-show="stateManage.showPsd" @click="stateManage.showPsd=false">隐藏</van-button>
        <van-button class="btn" type="primary" v-show="!stateManage.showPsd" @click="stateManage.showPsd=true">显示</van-button>
        <van-button class="btn" type="success" @click="exportData">导出</van-button>
        <van-button class="btn" type="success" @click="stateManage.importShow = true">导入</van-button>
      </div>
      <div>
        <van-search v-model="searchWord"  class="search"  placeholder="请输入搜索关键词" />
      </div>
    </div>

    <div class="content">
      <template v-for="account in accounts">
        <div class="card">
          <div class="col text" @click="copyData(account.name)">{{ account.name }}</div>
          <div class="col text" @click="copyData(account.account)">{{ account.account }} </div>
          <div class="col text" @click="copyData(account.psd)">{{ stateManage.showPsd?account.psd:'********' }}</div>
          <div class="col text" @click="copyData(account.memo)">{{ account.memo }}</div>
          <div class="flex center evenly col">
            <van-button plain type="primary" size="small" @click="editAccount(account)">修改</van-button>
            <van-button plain type="danger" size="small" @click="delAccount(account)">删除</van-button>
          </div>
        </div>
      </template>
    </div>



    <van-popup v-model:show="stateManage.editAccountShow" class="modal">
      <div><span>新增账号</span></div>
      <van-field v-model="account.name" label="名称"/>
      <van-field v-model="account.account" label="账号"/>
      <van-field v-model="account.psd" label="密码"/>
      <van-field v-model="account.memo" label="备注"/>

      <div class="flex center evenly operate">
        <van-button class="btn" type="primary" @click="saveOrUpdateAccount">保存</van-button>
        <van-button class="btn" type="danger" @click="cancelSaveAccount">取消</van-button>
      </div>


    </van-popup>

    <van-popup v-model:show="stateManage.importShow" class="modal import">
      <div><span>导入项目</span></div>
      <div class="flex col">
        <van-uploader accept=".txt" result-type="text" :after-read="afterRead">
          <van-button icon="plus" type="primary">上传文件</van-button>
        </van-uploader>
        <div>{{ file.file.name }}</div>
      </div>
      <div class="flex col">
        <van-button type="primary" @click="importProject">导入</van-button>
        <van-button type="danger" @click="cancelImport">取消</van-button>
      </div>

    </van-popup>

  </div>
</template>
<script setup>
import {accountManage} from "../entity/accountManage.js";
import {onMounted, reactive, ref, computed, watch} from 'vue'
import {accountData} from "../entity/accountData.js";
import {saveAs} from 'file-saver';
import {showConfirmDialog, showDialog, showNotify} from "vant";

let searchWord = ref('')
const accounts = reactive([])
const _accounts = reactive([])
const account = reactive(accountData.newAccount())
//1:新增  2：修改
let editMode = ref(1)
const stateManage = reactive({
  editAccountShow: false,
  importShow: false,
  showPsd:false,
})


onMounted(() => {
  getAllAccount()
})
const getAllAccount = async () => {
  let p = await accountManage.getAll()
  accounts.length = 0
  _accounts.length = 0
  if (p) {
    accounts.push(...p)
    //按创建时间排序
    accounts.sort((a, b) => b.t - a.t)
    _accounts.push(...accounts)
    filterAccount()
  }
}

watch(searchWord, () => {
  filterAccount()
})

const filterAccount = () => {
  let temp = _accounts.filter(a => a.name.includes(searchWord.value))
  accounts.length = 0
  accounts.push(...temp)
}
const addAccount = () => {
  Object.assign(account, accountData.newAccount())
  stateManage.editAccountShow = true
  editMode.value = 1
}
const editAccount = (acc) => {
  Object.assign(account, accountData.newAccount())
  Object.assign(account, acc)
  stateManage.editAccountShow = true
  editMode.value = 2
}
const saveOrUpdateAccount = () => {
  accountManage.saveOrUpdate(JSON.stringify(account))
  getAllAccount()
  stateManage.editAccountShow = false
}
const cancelSaveAccount = () => {
  stateManage.editAccountShow = false
}


const delAccount = (acc) => {
  showConfirmDialog({
    title: `删除操作`,
    message: `确认删除 ${acc.name} 吗？`,
    confirmButtonColor: 'red'
  }).then(() => {
        accountManage.delById(acc.id)
        getAllAccount()
  }).catch(() => {
        // on cancel
  });
}
const exportData = () => {
  let blob = new Blob([JSON.stringify(accounts)], {type: "text/plain;charset=utf-8"});
  saveAs(blob, '账号数据');
}
const file = ref({
  file: {
    name: ''
  }
})
const afterRead = (_file) => {
  console.log('afterRead', _file);
  file.value = _file
}


const importProject = () => {
  let accs = []
  // console.log('file',file.value.content);
  Object.assign(accs, JSON.parse(file.value.content))
  for (let acc of accs) {
    accountManage.saveOrUpdate(JSON.stringify(acc))
  }
  getAllAccount()
  stateManage.importShow = false
}
const cancelImport = () => {
  stateManage.importShow = false
  file.value = {
    file: {
      name: ''
    }
  }
}

const copyData = (data) => {
  navigator.clipboard.writeText(data)
      .then(() => {
        showNotify({
          message: '复制成功！',
          color: '#000000',
          background: '#67d59b',
          duration: 500,
        });
        console.log('Text copied to clipboard...')
      })
      .catch(err => {
        console.log('Something went wrong', err);
      })
}

</script>
<style scoped>
.flex {
  display: flex;
}

.center {
  text-align: center;
  justify-content: center;
  align-items: center;
}
.fix{
  position: fixed;
  top:0
}
.search {
  /*width: 45%;*/
  /*margin: 10px;*/
  --van-search-background:trasparent;
}

.evenly {
  justify-content: space-evenly;
}

.operate {
  margin: 10px;
}
.operate-top{
  background-color: white;
  z-index: 10;
  width: 100%;
  max-width: 1280px;
  padding-top: 10px;
}

.modal {
  border-radius: 10px;
}
.content{
  margin-top: 100px;
}
.card {
  border: 1px solid #67d59b;
  border-radius: 10px;
  padding: 10px;
  margin: 10px;
  background-color: #cafae1;

}
.text{
  /*user-select: all;*/
  /*-moz-user-select: all;*/
  /*-webkit-user-select: all;*/
  /*-ms-user-select: all;*/
}
.col {
  margin: 8px;
}

.btn {
  margin: 0 3px;
}

</style>